<?php
/**
 * Created by PhpStorm.
 * @User: 王崇全
 * @Date: 2018/10/31 12:31
 */

namespace app\common\model;

use think\Db;

/**
 * Class 站内信
 * @author  王崇全
 * @date    2018/10/31 14:06
 * @package app\common\model
 */
class Msg
{
    //表名
    private const TAB_NAME      = "msg";
    private const TAB_USER_NAME = "user";

    // 系统发件人编号
    private const SYS_SENDER    = 0;

    /**
     * 发送消息
     * @author 王崇全
     * @date   2018/10/31 13:52
     * @param int    $to      收信人ID
     * @param string $content 内容
     * @param int    $from    发信人ID, 默认为系统
     * @return bool
     * @throws
     */
    public function send(int $to, string $content, int $from = self::SYS_SENDER)
    : bool {

        if (mb_strlen($content) > 1024) {
            throw new \Exception("消息内容不能超过1024个字");
        }

        try {
            return Db::name(self::TAB_NAME)
              ->insert([
                  "from"        => $from,
                  "to"          => $to,
                  "content"     => $content,
                  "create_time" => date("Y-m-d H:i:s"),
                  "read_time"   => date("Y-m-d H:i:s", 0),
              ]) ? true : false;
        } catch (\Exception $e) {
            throw new \Exception("消息发送失败");
        }
    }

    /**
     * 设为已读
     * @author 王崇全
     * @date
     * @param int $id       消息编号
     * @param int $user_id  用户编号
     * @return bool
     * @throws \Exception
     */
    public function read(int $id,int $user_id)
    : bool {
        try {
            return Db::name(self::TAB_NAME)
                ->where('to',$user_id)
                ->where('id',$id)
              ->setField("read_time", date("Y-m-d H:i:s")) ? true : false;
        } catch (\Exception $e) {
            throw new \Exception("消息阅读失败");
        }
    }

    /**
     * 消息列表
     * @author 王崇全
     * @date   2018/10/31 13:58
     * @param array $where    检索条件 [
     *                        "from"=>发信人,
     *                        "to"=>收信人,
     *                        "is_read"=>是否已读, // bool
     *                        ]
     * @param int   $page     页码
     * @param int   $pageSize 页幅
     * @return array 消息列表 [count=>总数,list=>[
     *                        "id"=>编号,
     *                        "from"=>发信人,
     *                        "to"=>收信人,
     *                        "content"=>内容,
     *                        "create_time"=>发送时间,
     *                        "read_time"=>阅读时间,
     *                        ]]
     * @throws
     */
    public function list(array $where = [], int $page = DEF_PAGE_NO, int $pageSize = DEF_PAGE_SIZE)
    : array {

        $db = Db::name(self::TAB_NAME)->alias('m');
        $db->join(self::TAB_USER_NAME.' u','m.to = u.id','left');

        if (isset($where["name"])) {
            $db->where("u.name|u.tel", $where["name"]);
        }

        if (isset($where["to"])) {
            $db->where("m.to", $where["to"]);
        }

        if (isset($where["is_read"])) {
            $op = $where["is_read"] ? "> TIME" : "=";
            $o  = date("Y-m-d H:i:s", 0);
            $db->where("m.read_time", $op, $o);
        }

        if(isset($where['agent_name'])) {
            $a      = new Admin();
            $agent  = $a->getAdminByName($where['agent_name']);
            if($agent) {
                $agent_id = $agent['id'];
                $ids = $a->getIds($agent_id);
            } else {
                $ids = 0;
            }

            $db->where('u.admin_id','in',$ids);
        }


        //查询总数
        $count = $db->count("m.id");
        if ($count < 1) {
            return [
                "count" => 0,
                "list"  => [],
            ];
        }

        //列表
        $list = $db->field([
            "m.id",
            "m.from",
            "m.to",
            "m.content",
            "m.create_time",
            "m.read_time",
            "u.name",
            "u.tel",
            "u.admin_id"
        ])
                   ->order(["m.id" => "DESC"])
                   ->page($page, $pageSize)
                   ->select();

        $a          = new Admin();
        $admin      = $a->getAdmin();

        foreach ($list as $key => $val) {
            $list[$key]['admin_name']     = $admin[$val['admin_id']]['name'];
        }

        return [
            "count" => $count,
            "list"  => $list,
        ];

    }

    /**
     * 消息详情
     * @author 王海东
     * @date
     * @param int $id   站内信编号
     * @return array
     * @throws \Exception
     */
    public function detail(int $id)
    :array {
        try {
            $data = Db::name(self::TAB_NAME)
              ->alias('m')
              ->field('m.content,m.read_time,m.create_time,u.name,u.tel')
              ->join(self::TAB_USER_NAME.' u','m.to = u.id','right')
              ->where('m.id',$id)
              ->find();
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        return $data;
    }
}